package net.xdclass.video.crawler.service.Impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.xdclass.video.crawler.service.MoviesService;
import net.xdclass.video.entity.Details;
import net.xdclass.video.entity.FileOne;
import net.xdclass.video.entity.Images;
import net.xdclass.video.entity.Movie;
import net.xdclass.video.mapper.DetailsMapper;
import net.xdclass.video.mapper.FileMapper;
import net.xdclass.video.mapper.ImagesMapper;
import net.xdclass.video.mapper.MovieMapper;
import net.xdclass.video.service.DetailsService;
import net.xdclass.video.service.ImagesService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.System.*;

@Service
public class MoviesServiceImpl implements MoviesService {
    @Autowired
    private ImagesMapper imagesMapper;
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private DetailsMapper detailsMapper;

    private static final String FILE_UPLOAD_PATH_Movie= getProperty("user.dir")
            + File.separator
            + "src" + File.separator
            + "main" + File.separator
            + "resources"
            + File.separator
            + "static/files" + File.separator
            + "image" + File.separator
            +"Movie"+File.separator;

    private static final String FILE_UPLOAD_PATH_Teleplay= getProperty("user.dir")
            + File.separator
            + "src" + File.separator
            + "main" + File.separator
            + "resources"
            + File.separator
            + "static/files" + File.separator
            + "image" + File.separator
            +"teleplay"+File.separator;
    private static final String FILE_UPLOAD_PATH_Animation= getProperty("user.dir")
            + File.separator
            + "src" + File.separator
            + "main" + File.separator
            + "resources"
            + File.separator
            + "static/files" + File.separator
            + "image" + File.separator
            +"animation"+File.separator;

    private static final String FILE_UPLOAD_PATH_Variety= getProperty("user.dir")
            + File.separator
            + "src" + File.separator
            + "main" + File.separator
            + "resources"
            + File.separator
            + "static/files" + File.separator
            + "image" + File.separator
            +"variety"+File.separator;


    private WebDriver chromeDriver; // 用于关闭ChromeDriver

    @Value("${chromedriverPath}")
    public String chromedriverPath;
    @Override
    public void movie() {
        try {
            // 确保 ChromeDriver 路径已设置
//            if (chromedriverPath == null || chromedriverPath.isEmpty()) {
//                out.println("ChromeDriver 路径未设置");
//
//            }
//            System.setProperty("webdriver.chrome.driver", chromedriverPath);
//            System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--remote-allow-origins=*");
            chromeDriver = new ChromeDriver(chromeOptions);

            for (int y = 1; y <= 400; y++) {
                String urls = "https://lzi888.com/index.php/vod/show/id/1/page/" + y +".html ";
                out.println("正在爬取：" + urls);

                Document document = Jsoup.connect(urls).get();
                Elements element = document.select(".module-poster-item.module-item");

                for (Element elements : element) {
                    String href = elements.select("a").attr("href");  //获取进入详情页url

                    String imgUrls = elements.select("img").attr("data-original"); //封面url
                    if (imgUrls == null) {
                        String imgUrlTwo = elements.select("img").attr("data-original"); //封面url
                        imgUrls = imgUrlTwo;
                    }

                    String url1 = "https://lzi888.com/" + href;
                    String img = "https://lzi888.com/" + imgUrls;


                    Document document1 = Jsoup.connect(url1).get();

                    //详情页界面
                    Elements elements2 = document1.select(".content");

                    if (elements2 == null || elements2.isEmpty()) {
                        out.println("未找到内容元素");
                        continue;
                    }

                    for (Element element2 : elements2) {
                        String title = element2.select("h1").text();  //标题
                        String intro = element2.select("p").text();   //简介
                        String titles = element2.select("a.module-play-list-link").attr("href");  //进入视频界面url
                        if (titles == null || titles.isEmpty()) {
                            continue;
                        }
                        String VideoUrl = "https://lzi888.com/" + titles;

                        Elements element3 = element2.select(".module-info-tag-link a");

                        // 动态检测并分配字段
                        String year = element3.size() > 0 ? element3.get(0).text() : "";   //年份
                        String country = element3.size() > 1 ? element3.get(1).text() : "";  //国家

                        // 拼接剩下的分类字段，使用 "/" 进行分隔
                        StringBuilder genre = new StringBuilder();
                        for (int i = 2; i < element3.size(); i++) {
                            if (i > 2) {
                                genre.append("/"); // 添加斜杠分隔符
                            }
                            genre.append(element3.get(i).text());
                        }
                        // 将 StringBuilder 转换为 String
                        String genreString = genre.toString();  //剧情


// 用于累积每部分的名字
                        StringBuilder directorsText = new StringBuilder();
                        StringBuilder writersText = new StringBuilder();
                        StringBuilder actorsText = new StringBuilder();

// 获取导演部分
                        Element directorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(导演))");
                        if (directorElement != null) {
                            Elements directors = directorElement.select(".module-info-item-content a");
                            for (int i = 0; i < directors.size(); i++) {
                                directorsText.append(directors.get(i).text());
                                if (i < directors.size() - 1) {
                                    directorsText.append(" / ");  // 添加斜杠
                                }
                            }
                        }

// 获取编剧部分
                        Element writerElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(编剧))");
                        if (writerElement != null) {
                            Elements writers = writerElement.select(".module-info-item-content a");
                            for (int i = 0; i < writers.size(); i++) {
                                writersText.append(writers.get(i).text());
                                if (i < writers.size() - 1) {
                                    writersText.append(" / ");  // 添加斜杠
                                }
                            }
                        }

// 获取主演部分
                        Element actorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(主演))");
                        if (actorElement != null) {
                            Elements actors = actorElement.select(".module-info-item-content a");
                            for (int i = 0; i < actors.size(); i++) {
                                actorsText.append(actors.get(i).text());
                                if (i < actors.size() - 1) {
                                    actorsText.append(" / ");  // 添加斜杠
                                }
                            }
                        }

                        // 获取更新部分
                        Element updateElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(更新))");
                        String update = updateElement.select(".module-info-item-content").text();

                        // 输出累积结果


                        // 输出结果
//                    out.println("标题"+title);
//                    out.println("封面"+img);
//                    out.println("年份: " + year);
//                    out.println("国家: " + country);
//                    out.println("类型: " + genreString);
//                    out.println("简介"+intro);
//                    out.println("导演: " + directorsText.toString());
//                    out.println("编剧: " + writersText.toString());
//                    out.println("主演: " + actorsText.toString());
//                    out.println("更新: " + update);
//                    out.println("视频页面url"+VideoUrl);

                        if (VideoUrl.equals("https://lzi888.com/")) {
                            continue;
                        }
                        String type = "电影";
                        String cover = imgUrl(img, title, type);


                        Details details = new Details();
                        details.setName(title);
                        details.setType("电影");
                        details.setStatus(1);
                        details.setActors(actorsText.toString());
                        details.setDirector(directorsText.toString());
                        details.setYear(Integer.valueOf(year));
                        details.setCollect("2000");
                        details.setQuantity("2000");
                        details.setClassify(genreString);
                        details.setDescription(intro);
                        details.setCover(cover);
                        details.setGenre(genreString);
                        details.setWriter(writersText.toString());
                        details.setCountry(country);
                        detailsMapper.insert(details);

//                    Movie movie = new Movie();
//                    movie.setTitle(title);
//                    movie.setCover(cover);
//                    movie.setType(genreString);
//                    movie.setYear(year);
//                    movie.setCountry(country);
//                    movie.setPot(intro);
//                    movie.setDirector(directorsText.toString());
//                    movie.setLanguage(actorsText.toString());
//                    movie.setWriter(writersText.toString());
//                    movie.setRenewal(update);
//                    movie.setGenre(genreString);
//                    movieMapper.insert(movie);


                        chromeDriver.get(VideoUrl);
                        waitForPageLoad(chromeDriver);

                        List<WebElement> elements3 = chromeDriver.findElements(By.cssSelector("#playleft > iframe"));
                        for (WebElement elemen3 : elements3) {
                            String Url = elemen3.getAttribute("src");
//                        out.println("视频url: " + Url);
                            // 查找 'url=' 在字符串中的位置
                            int index = Url.indexOf("url=");
                            // 如果找到了 'url='，提取后面的内容
                            String extractedUrl = null;
                            if (index != -1) {
                                extractedUrl = Url.substring(index + 4); // 4 是 "url=" 的长度
                                out.println("提取的链接: " + extractedUrl);
                            } else {
                                out.println("未找到 'url=' 参数。");
                            }
                            FileOne fileOne = new FileOne();
                            fileOne.setName(title);
                            fileOne.setUrl(extractedUrl);
                            fileOne.setType("index.m3u8");
                            fileOne.setDiversity("正片");
                            QueryWrapper<Details> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("name", title);
                            Details movieOne = detailsMapper.selectOne(queryWrapper);
                            Integer movieOneId = movieOne.getDetailsId();
                            fileOne.setDetailsId(movieOneId);
                            fileMapper.insert(fileOne);
                        }
                    }
                }
            }
            } catch(Exception e){
                out.println("发生错误: " + e.getMessage());

            } finally{
                if (chromeDriver != null) {
                    chromeDriver.quit();
                }
            }

    }

    @Override
    public void teleplay() {
        try {
            // ChromeDriver 配置
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--remote-allow-origins=*");
            chromeDriver = new ChromeDriver(chromeOptions);
            for (int y = 2; y <= 400; y++) {
                String urls = "https://lzi888.com/index.php/vod/show/id/2/page/"+y+".html";
                out.println("正在爬取：" + urls);

                // 使用 Jsoup 获取页面内容
                Document document = Jsoup.connect(urls).get();
                Elements element = document.select(".module-poster-item.module-item");

                for (Element elements : element) {
                    String href = elements.select("a").attr("href");  //获取详情页url
                    String imgUrls = elements.select("img").attr("data-original"); //封面url

                    String url1 = "https://lzi888.com/" + href;
                    String img = "https://lzi888.com/" + imgUrls;

                    Document document1 = Jsoup.connect(url1).get();
                    Elements elements2 = document1.select(".content");

                    if (elements2 == null || elements2.isEmpty()) {
                        out.println("未找到内容元素，可能是无效页面: " + url1);
                        continue;
                    }

                    for (Element element2 : elements2) {
                        // 获取标题
                        String title = element2.select("h1").text();
                        if (title == null || title.isEmpty()) {
                            out.println("未找到标题，跳过该条记录");
                            continue;
                        }

                        // 获取简介
                        String intro = element2.select("p").text();
                        if (intro.contains("本站所有内容")) {
                            out.println("跳过无效内容");
                            continue;
                        }

                        // 获取年份、国家、类型等信息
                        Elements element3 = element2.select(".module-info-tag-link a");
                        String year = element3.size() > 0 ? element3.get(0).text() : "";   //年份
                        String country = element3.size() > 1 ? element3.get(1).text() : "";  //国家

                        // 拼接剩余的分类字段
                        StringBuilder genre = new StringBuilder();
                        for (int i = 2; i < element3.size(); i++) {
                            if (i > 2) {
                                genre.append("/"); // 添加斜杠分隔符
                            }
                            genre.append(element3.get(i).text());
                        }
                        String genreString = genre.toString();  //剧情

                        // 获取导演、编剧、主演
                        StringBuilder directorsText = new StringBuilder();
                        StringBuilder writersText = new StringBuilder();
                        StringBuilder actorsText = new StringBuilder();

                        // 获取导演部分
                        Element directorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(导演))");
                        if (directorElement != null) {
                            Elements directors = directorElement.select(".module-info-item-content a");
                            for (int i = 0; i < directors.size(); i++) {
                                directorsText.append(directors.get(i).text());
                                if (i < directors.size() - 1) {
                                    directorsText.append(" / ");
                                }
                            }
                        }

                        // 获取编剧部分
                        Element writerElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(编剧))");
                        if (writerElement != null) {
                            Elements writers = writerElement.select(".module-info-item-content a");
                            for (int i = 0; i < writers.size(); i++) {
                                writersText.append(writers.get(i).text());
                                if (i < writers.size() - 1) {
                                    writersText.append(" / ");
                                }
                            }
                        }

                        // 获取主演部分
                        Element actorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(主演))");
                        if (actorElement != null) {
                            Elements actors = actorElement.select(".module-info-item-content a");
                            for (int i = 0; i < actors.size(); i++) {
                                actorsText.append(actors.get(i).text());
                                if (i < actors.size() - 1) {
                                    actorsText.append(" / ");
                                }
                            }
                        }

                        String type = "电视剧";
                        String cover = imgUrl(img, title, type);


                        Details details = new Details();
                        details.setName(title);
                        details.setType("电视剧");
                        details.setStatus(1);
                        details.setActors(actorsText.toString());
                        details.setDirector(directorsText.toString());
                        details.setYear(Integer.valueOf(year));
                        details.setCollect("2000");
                        details.setQuantity("2000");
                        details.setClassify(genreString);
                        details.setDescription(intro);
                        details.setCover(cover);
                        details.setGenre(genreString);
                        details.setWriter(writersText.toString());
                        details.setCountry(country);
                        detailsMapper.insert(details);

                        // 输出获取到的信息
//                    out.println("url: " + url1);
//                    out.println("标题: " + title);
//                    out.println("封面: " + img);
//                    out.println("年份: " + year);
//                    out.println("国家: " + country);
//                    out.println("类型: " + genreString);
//                    out.println("简介: " + intro);
//                    out.println("导演: " + directorsText.toString());
//                    out.println("编剧: " + writersText.toString());
//                    out.println("主演: " + actorsText.toString());

                        // 获取集数信息并处理视频链接
                        Element firstInterfaceDiv = element2.select(".module-list.sort-list.tab-list.his-tab-list").first();
                        if (firstInterfaceDiv != null) {
                            Elements links = firstInterfaceDiv.select("a.module-play-list-link");
                            String VideoUrl = null;

                            for (Element link : links) {
                                String es = link.select("span").text(); // 获取集数
                                String titles = link.attr("href"); // 获取视频链接
                                VideoUrl = "https://lzi888.com/" + titles;

                                out.println("集数: " + es + " 视频页面url: " + VideoUrl);

                                if (VideoUrl.equals("https://lzi888.com/")) {
                                    continue;
                                }

                                // 访问视频页面并提取视频链接
                                chromeDriver.get(VideoUrl);
                                waitForPageLoad(chromeDriver);

                                List<WebElement> elements3 = chromeDriver.findElements(By.cssSelector("#playleft > iframe"));
                                for (WebElement elemen3 : elements3) {
                                    String Url = elemen3.getAttribute("src");
                                    int index = Url.indexOf("url=");
                                    String extractedUrl = null;
                                    if (index != -1) {
                                        extractedUrl = Url.substring(index + 4);
                                        out.println("提取的链接: " + extractedUrl);
                                    } else {
                                        out.println("未找到 'url=' 参数。");
                                    }
                                    FileOne fileOne = new FileOne();
                                    fileOne.setName(title);
                                    fileOne.setUrl(extractedUrl);
                                    fileOne.setType("index.m3u8");
                                    fileOne.setDiversity(processEpisode(es));
                                    QueryWrapper<Details> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.eq("name", title);
                                    Details movieOne = detailsMapper.selectOne(queryWrapper);
                                    Integer movieOneId = movieOne.getDetailsId();
                                    fileOne.setDetailsId(movieOneId);
                                    fileMapper.insert(fileOne);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            out.println("发生错误: " + e.getMessage());
        } finally {
            if (chromeDriver != null) {
                chromeDriver.quit();
            }
        }
    }

    @Override
    public void varietyCrawling() {
        try {
            // ChromeDriver 配置
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--remote-allow-origins=*");
            chromeDriver = new ChromeDriver(chromeOptions);

            String urls = "https://lzi888.com/index.php/vod/show/id/3.html";
            out.println("正在爬取：" + urls);

            // 使用 Jsoup 获取页面内容
            Document document = Jsoup.connect(urls).get();
            Elements element = document.select(".module-poster-item.module-item");

            for (Element elements : element) {
                String href = elements.select("a").attr("href");  //获取详情页url
                String imgUrls = elements.select("img").attr("data-original"); //封面url

                String url1 = "https://lzi888.com/" + href;
                String img = "https://lzi888.com/" + imgUrls;

                Document document1 = Jsoup.connect(url1).get();
                Elements elements2 = document1.select(".content");

                if (elements2 == null || elements2.isEmpty()) {
                    out.println("未找到内容元素，可能是无效页面: " + url1);
                    continue;
                }

                for (Element element2 : elements2) {
                    // 获取标题
                    String title = element2.select("h1").text();
                    if (title == null || title.isEmpty()) {
                        out.println("未找到标题，跳过该条记录");
                        continue;
                    }

                    // 获取简介
                    String intro = element2.select("p").text();
                    if (intro.contains("本站所有内容")) {
                        out.println("跳过无效内容");
                        continue;
                    }

                    // 获取年份、国家、类型等信息
                    Elements element3 = element2.select(".module-info-tag-link a");
                    String year = element3.size() > 0 ? element3.get(0).text() : "";   //年份
                    String country = element3.size() > 1 ? element3.get(1).text() : "";  //国家

                    // 拼接剩余的分类字段
                    StringBuilder genre = new StringBuilder();
                    for (int i = 2; i < element3.size(); i++) {
                        if (i > 2) {
                            genre.append("/"); // 添加斜杠分隔符
                        }
                        genre.append(element3.get(i).text());
                    }
                    String genreString = genre.toString();  //剧情

                    // 获取导演、编剧、主演
                    StringBuilder directorsText = new StringBuilder();
                    StringBuilder actorsText = new StringBuilder();

                    // 获取导演部分
                    Element directorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(导演))");
                    if (directorElement != null) {
                        Elements directors = directorElement.select(".module-info-item-content a");
                        for (int i = 0; i < directors.size(); i++) {
                            directorsText.append(directors.get(i).text());
                            if (i < directors.size() - 1) {
                                directorsText.append(" / ");
                            }
                        }
                    }


                    // 获取主演部分
                    Element actorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(主演))");
                    if (actorElement != null) {
                        Elements actors = actorElement.select(".module-info-item-content a");
                        for (int i = 0; i < actors.size(); i++) {
                            actorsText.append(actors.get(i).text());
                            if (i < actors.size() - 1) {
                                actorsText.append(" / ");
                            }
                        }
                    }

                    String type="综艺";
                    String cover = imgUrl(img, title,type);

//
                    Details details = new Details();
                    details.setName(title);
                    details.setType("综艺");
                    details.setStatus(1);
                    details.setActors(actorsText.toString());
                    details.setDirector(directorsText.toString());
                    details.setYear(Integer.valueOf(year));
                    details.setCollect("2000");
                    details.setQuantity("2000");
                    details.setClassify(genreString);
                    details.setDescription(intro);
                    details.setCover(cover);
                    details.setGenre(genreString);
                    details.setCountry(country);
                    detailsMapper.insert(details);

                    // 输出获取到的信息
//                    out.println("url: " + url1);
//                    out.println("标题: " + title);
//                    out.println("封面: " + img);
//                    out.println("年份: " + year);
//                    out.println("国家: " + country);
//                    out.println("类型: " + genreString);
//                    out.println("简介: " + intro);
//                    out.println("导演: " + directorsText.toString());
//                    out.println("主演: " + actorsText.toString());

                    // 获取集数信息并处理视频链接
                    Element firstInterfaceDiv = element2.select(".module-list.sort-list.tab-list.his-tab-list").first();
                    if (firstInterfaceDiv != null) {
                        Elements links = firstInterfaceDiv.select("a.module-play-list-link");
                        String VideoUrl = null;

                        for (Element link : links) {
                            String es = link.select("span").text(); // 获取集数
                            String titles = link.attr("href"); // 获取视频链接
                            VideoUrl = "https://lzi888.com/" + titles;

                            out.println("集数: " +es + " 视频页面url: " + VideoUrl);

                            if (VideoUrl.equals("https://lzi888.com/")) {
                                continue;
                            }

                            // 访问视频页面并提取视频链接
                            chromeDriver.get(VideoUrl);
                            waitForPageLoad(chromeDriver);

                            List<WebElement> elements3 = chromeDriver.findElements(By.cssSelector("#playleft > iframe"));
                            for (WebElement elemen3 : elements3) {
                                String Url = elemen3.getAttribute("src");
                                int index = Url.indexOf("url=");
                                String extractedUrl = null;
                                if (index != -1) {
                                    extractedUrl = Url.substring(index + 4);
                                    out.println("提取的链接: " + extractedUrl);
                                } else {
                                    out.println("未找到 'url=' 参数。");
                                }
                                FileOne fileOne = new FileOne();
                                fileOne.setName(title);
                                fileOne.setUrl(extractedUrl);
                                fileOne.setType("index.m3u8");
                                fileOne.setDiversity(es);
                                QueryWrapper<Details> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("name", title);
                                Details movieOne = detailsMapper.selectOne(queryWrapper);
                                Integer movieOneId = movieOne.getDetailsId();
                                fileOne.setDetailsId(movieOneId);
                                fileMapper.insert(fileOne);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            out.println("发生错误: " + e.getMessage());
        } finally {
            if (chromeDriver != null) {
                chromeDriver.quit();
            }
        }
    }
    //动漫

    @Override
    public void animationCrawling() {
        try {
            // ChromeDriver 配置
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--remote-allow-origins=*");
            chromeDriver = new ChromeDriver(chromeOptions);

            String urls = "https://lzi888.com/index.php/vod/show/id/4.html";
            out.println("正在爬取：" + urls);

            // 使用 Jsoup 获取页面内容
            Document document = Jsoup.connect(urls).get();
            Elements element = document.select(".module-poster-item.module-item");

            for (Element elements : element) {
                String href = elements.select("a").attr("href");  //获取详情页url
                String imgUrls = elements.select("img").attr("data-original"); //封面url

                String url1 = "https://lzi888.com/" + href;
                String img = "https://lzi888.com/" + imgUrls;

                Document document1 = Jsoup.connect(url1).get();
                Elements elements2 = document1.select(".content");

                if (elements2 == null || elements2.isEmpty()) {
                    out.println("未找到内容元素，可能是无效页面: " + url1);
                    continue;
                }

                for (Element element2 : elements2) {
                    // 获取标题
                    String title = element2.select("h1").text();
                    if (title == null || title.isEmpty()) {
                        out.println("未找到标题，跳过该条记录");
                        continue;
                    }

                    // 获取简介
                    String intro = element2.select("p").text();
                    if (intro.contains("本站所有内容")) {
                        out.println("跳过无效内容");
                        continue;
                    }

                    // 获取年份、国家、类型等信息
                    Elements element3 = element2.select(".module-info-tag-link a");
                    String year = element3.size() > 0 ? element3.get(0).text() : "";   //年份
                    String country = element3.size() > 1 ? element3.get(1).text() : "";  //国家

                    // 拼接剩余的分类字段
                    StringBuilder genre = new StringBuilder();
                    for (int i = 2; i < element3.size(); i++) {
                        if (i > 2) {
                            genre.append("/"); // 添加斜杠分隔符
                        }
                        genre.append(element3.get(i).text());
                    }
                    String genreString = genre.toString();  //剧情

                    // 获取导演、编剧、主演
                    StringBuilder directorsText = new StringBuilder();
                    StringBuilder actorsText = new StringBuilder();

                    // 获取导演部分
                    Element directorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(导演))");
                    if (directorElement != null) {
                        Elements directors = directorElement.select(".module-info-item-content a");
                        for (int i = 0; i < directors.size(); i++) {
                            directorsText.append(directors.get(i).text());
                            if (i < directors.size() - 1) {
                                directorsText.append(" / ");
                            }
                        }
                    }


                    // 获取主演部分
                    Element actorElement = element2.selectFirst(".module-info-item:has(.module-info-item-title:contains(主演))");
                    if (actorElement != null) {
                        Elements actors = actorElement.select(".module-info-item-content a");
                        for (int i = 0; i < actors.size(); i++) {
                            actorsText.append(actors.get(i).text());
                            if (i < actors.size() - 1) {
                                actorsText.append(" / ");
                            }
                        }
                    }
////
                    String type="动漫";
                    String cover = imgUrl(img, title,type);
                    out.println("图片"+cover);
                    Details details = new Details();
                    details.setName(title);
                    details.setType("动漫");
                    details.setStatus(1);
                    details.setActors(actorsText.toString());
                    details.setDirector(directorsText.toString());
                    details.setYear(Integer.valueOf(year));
                    details.setCollect("2000");
                    details.setQuantity("2000");
                    details.setClassify(genreString);
                    details.setDescription(intro);
                    details.setCover(cover);
                    details.setGenre(genreString);
                    details.setCountry(country);
                    detailsMapper.insert(details);

//                    out.println("url"+url1);
//                    // 输出获取到的信息
//                    out.println("url: " + url1);
//                    out.println("标题: " + title);
//                    out.println("封面: " + img);
//                    out.println("年份: " + year);
//                    out.println("国家: " + country);
//                    out.println("类型: " + genreString);
//                    out.println("简介: " + intro);
//                    out.println("导演: " + directorsText.toString());
//                    out.println("主演: " + actorsText.toString());

                    // 获取集数信息并处理视频链接
                    Element firstInterfaceDiv = element2.select(".module-list.sort-list.tab-list.his-tab-list").first();
                    if (firstInterfaceDiv != null) {
                        Elements links = firstInterfaceDiv.select("a.module-play-list-link");
                        String VideoUrl = null;

                        for (Element link : links) {
                            String es = link.select("span").text(); // 获取集数
                            String titles = link.attr("href"); // 获取视频链接
                            VideoUrl = "https://lzi888.com/" + titles;

//                            out.println("集数: " + processEpisode(es) + " 视频页面url: " + VideoUrl);

                            if (VideoUrl.equals("https://lzi888.com/")) {
                                continue;
                            }

                            // 访问视频页面并提取视频链接
                            chromeDriver.get(VideoUrl);
                            waitForPageLoad(chromeDriver);

                            List<WebElement> elements3 = chromeDriver.findElements(By.cssSelector("#playleft > iframe"));
                            for (WebElement elemen3 : elements3) {
                                String Url = elemen3.getAttribute("src");
                                int index = Url.indexOf("url=");
                                String extractedUrl = null;
                                if (index != -1) {
                                    extractedUrl = Url.substring(index + 4);
                                    out.println("提取的链接: " + extractedUrl);
                                } else {
                                    out.println("未找到 'url=' 参数。");
                                }
                                FileOne fileOne = new FileOne();
                                fileOne.setName(title);
                                fileOne.setUrl(extractedUrl);
                                fileOne.setType("index.m3u8");
                                fileOne.setDiversity(String.valueOf(processEpisode(es)));
                                QueryWrapper<Details> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("name", title);
                                Details movieOne = detailsMapper.selectOne(queryWrapper);
                                Integer movieOneId = movieOne.getDetailsId();
                                fileOne.setDetailsId(movieOneId);
                                fileMapper.insert(fileOne);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            out.println("发生错误: " + e.getMessage());
        } finally {
            if (chromeDriver != null) {
                chromeDriver.quit();
            }
        }
    }


    public String imgUrl(String imgUrl,String title,String types){
        String folderPath = null;
        if (types.equals("电影")){
            folderPath = FILE_UPLOAD_PATH_Movie;
        }else if(types.equals("电视剧")) {
            folderPath = FILE_UPLOAD_PATH_Teleplay;
        }else if(types.equals("动漫")){
            folderPath=FILE_UPLOAD_PATH_Animation;
        }else if(types.equals("综艺")){
            folderPath=FILE_UPLOAD_PATH_Variety;
        }

        File file=new File(folderPath);
        if (!file.exists()){
            file.mkdirs();
        }

        // 获取文件扩展名
        String type;
        type = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
        if (type.length()>4){
            type = "jpg";
        }
        String UUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
        String destinationPath = folderPath+ File.separator + UUID; // 本地文件路径
        // 将反斜杠替换为正斜杠
        String destinationPaths = destinationPath.replaceAll("\\\\", "/");
        out.println("===" + destinationPaths);
        String cover = null;
        try {
            //下载

            Map<String, Object> stringObjectMap = downLoadImage(imgUrl, destinationPaths,UUID,types);
            String fileName = (String) stringObjectMap.get("fileName");
            if (fileName==null){
                fileName=imgUrl;
            }else {
                fileName=fileName;
            }
            long fileSize = (long) stringObjectMap.get("fileSize");
            String md5 = (String) stringObjectMap.get("md5");
            cover= (String) stringObjectMap.get("cover");

            Images images=new Images();
            images.setCover(cover);
            images.setSize(fileSize);
            images.setOriginalFilename(fileName);
            images.setType(type);
            images.setMd5(md5);
            images.setName(title);
            imagesMapper.insert(images);


        } catch (Exception e) {
            err.println("Error downloading image: " + e.getMessage());
        }
        return cover;
    }
    public Map<String, Object> downLoadImage(String imageUrl, String destinationPath, String UUID,String types) {
        Map<String, Object> result = new HashMap<>();

        try {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            connection.setUseCaches(false); // 禁用缓存

            // 第一次打开连接，计算MD5哈希
            byte[] md5Bytes;
            try (InputStream inputStream = connection.getInputStream();
                 DigestInputStream digestInputStream = new DigestInputStream(inputStream, MessageDigest.getInstance("MD5"))
            ){
                byte[] bytes = new byte[4096];
                while (digestInputStream.read(bytes) != -1) {
                    // 读取流以计算哈希
                }
                md5Bytes = digestInputStream.getMessageDigest().digest();
            }

            String md5 = bytesToHex(md5Bytes);

            // 检查是否存在相同MD5的文件
            Images fileByMd5 = getFileByMd5(md5);
            String cover = null;
            if (fileByMd5 != null) {
                cover = fileByMd5.getCover();
                boolean exist = FileUtil.exist(FILE_UPLOAD_PATH_Variety + cover.substring(cover.lastIndexOf("/") + 1));
                if (!exist) {
                    // 重新打开连接以下载文件
                    connection = url.openConnection();
                    connection.setUseCaches(false);
                    try (InputStream downloadInputStream = connection.getInputStream();
                         OutputStream outputStream = new FileOutputStream(destinationPath)) {
                        byte[] bytes = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = downloadInputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, 0, bytesRead);
                        }
                    }
                    if (types.equals("电影")){
                        cover = "http://localhost:9090/files/image/movie/" + UUID;
                    }else if(types.equals("电视剧")){
                        cover = "http://localhost:9090/files/image/teleplay/" + UUID;
                    }else if(types.equals("动漫")){
                        cover = "http://localhost:9090/files/image/animation/" + UUID;
                    }else if(types.equals("综艺")){
                       cover = "http://localhost:9090/files/image/variety/" + UUID;
                    }

                }
            } else {
                // 重新打开连接以下载文件
                connection = url.openConnection();
                connection.setUseCaches(false);
                try (InputStream downloadInputStream = connection.getInputStream();
                     OutputStream outputStream = new FileOutputStream(destinationPath)) {
                    byte[] bytes = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = downloadInputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, bytesRead);
                    }
                }
                if (types.equals("电影")){
                    cover = "http://localhost:9090/files/image/movie/" + UUID;
                }else if(types.equals("电视剧")){
                    cover = "http://localhost:9090/files/image/teleplay/" + UUID;
                }else if(types.equals("动漫")){
                    cover = "http://localhost:9090/files/image/animation/" + UUID;
                }else if(types.equals("综艺")){
                    cover = "http://localhost:9090/files/image/variety/" + UUID;
                }

            }

            String fileName = new File(imageUrl).getName();
            long fileSize = new File(destinationPath).length();

            // 将值放入Map
            result.put("cover", cover);
            result.put("fileName", fileName);
            result.put("fileSize", fileSize);
            result.put("md5", md5);
            return result;

        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    //图片的md5 查看数据库有没有一样的
    private Images getFileByMd5(String md5) {
        QueryWrapper<Images> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("md5",md5);
        List<Images> filesList=imagesMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);

    }

    private void waitForPageLoad(WebDriver driver) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
    }


    // 处理集数的方法
    public  String  processEpisode(String episode) {
        if (episode.equals("正片")){
            return episode;
        }
        // 提取集数中的数字部分，假设输入为"第XX集"
        int num = Integer.parseInt(episode.substring(1, episode.length() - 1));

        if (num >= 1 && num <= 9) {
            return String.valueOf(num);  // 1到9集直接输出数字
        } else if (num >= 10 && num <= 10000) {
             // 取整10作为中间值
           return String.valueOf(num);
        } else {
            return episode;

        }
    }

}
